<template>
  <div class="class-list-add">
    <div class="crumbs-link my-reservation-add-link">
      <router-link to="/course2/class">评级列表</router-link>
      <router-link to="/course2/class-list">
        <i>></i>评课量表</router-link>
      <strong>
        <i>></i>编辑</strong>
    </div>
    <div class="class-list-add-cont">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px">
        <el-form-item label="量表名称" prop="name">
            <el-input class="cont_input" v-model="ruleForm.name" placeholder="20字符以内" maxlength="20"></el-input>
        </el-form-item>
        <el-form-item label="适用学段" prop="study_section_id">
          <el-select v-model="ruleForm.study_section_id" @change="getOrgLevel2" placeholder="请选择">
            <el-option v-for="(item, index) in orgLevel2" :label="item.name" :value="item.id" :key="index"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="适用年级" prop="grade_id">
          <el-select v-model="ruleForm.grade_id" @change="getSubject" placeholder="请选择年级">
            <el-option v-for="(item, index) in orgLevel3" :label="item.name" :value="item.id" :key="index"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="适用科目" prop="subject_id">
          <el-select v-model="ruleForm.subject_id" placeholder="请选择科目">
            <el-option v-for="(item, index) in orgSubject" :label="item.name" :value="item.id" :key="index"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="适用课型" prop="teaching_type">
          <el-select v-model="ruleForm.teaching_type" placeholder="请选择课型">
            <el-option label="新授课" :value="1"></el-option>
            <el-option label="复习课" :value="2"></el-option>
            <el-option label="评讲课" :value="3"></el-option>
            <el-option label="主题活动课" :value="4"></el-option>
          </el-select>
        </el-form-item>
        <div class="class-list-standard">
          <h3>评估标准</h3>
          <el-form-item label="标准总分" prop="total_score">
            <div>
              <i v-text="ruleForm.total_score"></i>
              <span>分</span>
            </div>
          </el-form-item>
          <el-form-item label="标准细则" prop="" class="catalog">
            <div class="catalog-">
              <el-tabs v-model="tabTempIndex" type="card" editable @edit="handleTabsEdit">
                <el-tab-pane v-for="(item, index) in ruleForm.info_data" :label="item.title" :name="item.name" :key="index">
                  <div class="catalog-cont">
                    <el-form label-position="left" :model="item" :ref="'rules' + index">
                      <el-row class="project-title clear">
                        <el-col :span="10">
                          <el-form-item prop="content" label-width="100px" label="项目名" :rules="[{ validator: checkSpace,required: true}]">
                            <el-input v-model="item.content" placeholder="10个字符以内" maxlength="10"></el-input>
                          </el-form-item>
                        </el-col>
                        <el-col :span="7" style="margin-left:9.5%;">
                          <el-form-item prop="" label="项目总分">
                            <el-input-number v-model="item.score" :disabled="true" :controls="false"></el-input-number>
                          </el-form-item>
                        </el-col>
                      </el-row>
                      <div class="catalog-list project-cont">
                        <template v-for="(course,inx) in item.children">
                          <el-form-item :key="inx">
                            <el-col :span="10">
                              <transition name="el-fade-in-linear">
                                <el-form-item :prop="'children.' + inx + '.content'" :label="`${inx+1}.子项内容`" label-width="100px" :rules="[{ validator: checkSpace,required: true}]">
                                  <el-input type="textarea" :rows="4" resize="none" v-model="course.content" placeholder="在此输入子项内容" maxlength="200">
                                  </el-input>
                                  <span class="word-sum">
                                    <i>{{course.content.length}}</i>/200</span>
                                </el-form-item>
                              </transition>
                            </el-col>
                            <el-col :span="7" :offset="2">
                              <el-form-item :prop="'children.' + inx + '.score'" label="设置分数" :rules="[{validator: checkScore, trigger: 'blur',required: true}]">
                                <el-input-number v-model="course.score" @blur="handleChange" :min="0" :max="100" :controls="false" placeholder="设置分数"></el-input-number>
                              </el-form-item>
                            </el-col>
                            <el-col :span="2" :offset="2">
                              <i class="el-icon-close" @click="removerEntryChild(index,inx)"></i>
                            </el-col>
                          </el-form-item>
                        </template>
                        <div class="catalog-list-btn buttonCSS">
                          <el-button type="primary" @click="newchildren(index)">添加子项目</el-button>
                        </div>
                      </div>
                    </el-form>
                  </div>
                </el-tab-pane>
              </el-tabs>
            </div>
          </el-form-item>
        </div>
        <el-form-item class="buttonCSS" label-width="0">
          <el-button @click="resetForm('ruleForm')" plain>取消</el-button>
          <el-button type="primary" @click="submitForm('ruleForm')">确定</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
export default {
    name: "",
    data() {
        return {
            ruleForm: {
                id: "",
                name: "",
                study_section_id: "",
                grade_id: "",
                subject_id: "",
                teaching_type: "",
                total_score: 0,
                info_data: [
                    {
                        title: "项目-1",
                        name: "1",
                        content: "",
                        score: 0,
                        children: [
                            {
                                content: "",
                                score: 0
                            }
                        ]
                    }
                ]
            },
            rules: {
                name: [
                    {
                        required: true,
                        message: "请输入量表名称",
                        trigger: "blur"
                    }
                ],
                study_section_id: [
                    { required: true, message: "请选择学段", trigger: "change" }
                ],
                grade_id: [
                    { required: true, message: "请选择年级", trigger: "change" }
                ],
                subject_id: [
                    { required: true, message: "请选择科目", trigger: "change" }
                ],
                teaching_type: [
                    { required: true, message: "请选择课型", trigger: "change" }
                ]
            },
            orgLevel2: [], //学段
            orgLevel3: [], //年级
            orgSubject: [], //科目
            tabTempIndex: "0"
        };
    },
    created() {
        this.getInfo();
    },
    methods: {
        //设置分数后计算总分
        handleChange(value) {
            this.ruleForm.total_score = 0;
            for (var i = this.ruleForm.info_data.length - 1; i >= 0; i--) {
                if (this.ruleForm.info_data[i].children.length > 0) {
                    this.ruleForm.info_data[i].score = 0;
                    var score_column = getOneColumn(
                        this.ruleForm.info_data[i].children,
                        "score"
                    );
                    for (var j = score_column.length - 1; j >= 0; j--) {
                        this.ruleForm.info_data[i].score += parseInt(
                            score_column[j]
                        );
                        this.ruleForm.total_score += parseInt(score_column[j]);
                    }
                }
            }
        },
        //课程目录
        handleTabsEdit(targetName, action) {
            if (action === "add") {
                let newTabIndex = this.ruleForm.info_data.length + 1;
                this.tabTempIndex = newTabIndex.toString();
                this.ruleForm.info_data.push({
                    title: `项目-${newTabIndex}`,
                    name: newTabIndex.toString(),
                    content: "",
                    score: 0,
                    children: [
                        {
                            title: "",
                            content: "",
                            score: 0
                        }
                    ]
                });
            } else if (action === "remove") {
                if (this.ruleForm.info_data.length === 1) {
                    this.$message.error("评估项不能为空");
                    return;
                }
                var tabs = deep_clone(this.ruleForm.info_data);
                var newtabs = [];
                var continue_ornot = false;
                var ivn = 0;
                for (var i = 0; i < tabs.length; i++) {
                    if (parseInt(tabs[i].name) === parseInt(targetName)) {
                        continue_ornot = true;
                        if (
                            parseInt(this.tabTempIndex) > 1 &&
                            i === parseInt(this.tabTempIndex)
                        ) {
                            this.tabTempIndex = parseInt(
                                this.tabTempIndex
                            ).toString();
                        } else if (parseInt(this.tabTempIndex) > i) {
                            this.tabTempIndex = (
                                parseInt(this.tabTempIndex) - 1
                            ).toString();
                        }
                        continue;
                    } else {
                        ivn = ivn + 1;
                        if (continue_ornot) {
                            tabs[i].title = `项目-${ivn}`;
                            tabs[i].name = ivn.toString();
                        }
                        newtabs.push(tabs[i]);
                    }
                }
                this.ruleForm.info_data = deep_clone(newtabs);
                this.handleChange(); //重计总分
            }
        },
        newchildren(index) {
            this.ruleForm.info_data[index].children.push({
                title: index + 1,
                content: "",
                score: 0
            });
        },
        removerEntryChild(index, index2) {
            if (this.ruleForm.info_data[index].children.length > 1) {
                this.ruleForm.info_data[index].children.splice(index2, 1);
                this.handleChange();
            } else {
                this.$message.error("子项不能为空");
                return;
            }
        },
        getOrgLevel2() {
            let success = res => {
                this.orgLevel2 = res.data;
                this.getOrgLevel3();
            };
            this.$ajax({
                url: "api/org/org",
                method: "get",
                params: {
                    level: 2,
                    pid: 1,
                    direction: "balance"
                },
                func: {
                    success: success
                }
            });
        },
        getOrgLevel3() {
            let success = res => {
                let data = res.data;
                if (data.length === 0) {
                    return;
                }
                this.orgLevel3 = data;
                this.getSubject();
            };
            this.$ajax({
                url: "api/org/org",
                method: "get",
                params: {
                    level: 3,
                    pid: this.ruleForm.study_section_id,
                    direction: "balance"
                },
                func: {
                    success: success
                }
            });
        },
        getSubject() {
            let success = res => {
                let data = res.data;
                this.orgSubject = data;
            };
            this.$ajax({
                url: "api/cate/subject",
                method: "get",
                params: {
                    type: 2,
                    org_id: this.ruleForm.grade_id,
                    status: 1
                },
                func: {
                    success: success
                }
            });
        },
        getInfo() {
            let success = data => {
                this.ruleForm = data.data;
                this.getOrgLevel2();
            };
            this.$ajax.get("api/teachingschedule/schedule_scale", {
                params: { schedule_id: this.$route.query.id },
                func: { success: success }
            });
        },
        saveLive() {
            let success = data => {
                this.$message.success(data.msg);
                setTimeout(() => {
                    this.$router.push({ path: "/course2/class-list" });
                }, 1000);
            };
            let fail = data => {
                let msg = "";
                if (typeof data.msg == "object") {
                    for (var i = 0; i <= data.msg.length - 1; i++) {
                        msg +=
                            '<p style="line-height:20px;color:#f56c6c">' +
                            data.msg[i] +
                            "</p>";
                    }
                } else {
                    msg = data.msg;
                }
                this.messageObj = this.$message({
                    duration: 3000,
                    type: "warning",
                    dangerouslyUseHTMLString: true,
                    message: msg
                });
            };
            this.$ajax.put(
                "api/teachingschedule/schedule_scale",
                this.ruleForm,
                {
                    func: { success: success, fail: fail }
                }
            );
        },
        submitForm(formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    this.formValid("verify");
                } else {
                    return false;
                }
            });
        },
        formValid(flag) {
            /*验证组件中所有的表单*/
            let forms = this.$refs;
            let endValids = [];
            for (let form in forms) {
                if (form.indexOf("rules") > -1) {
                    if (flag === "verify") {
                        forms[form][0].validate(valid => {
                            endValids.push(valid);
                        });
                    }
                    if (flag === "reset") {
                        forms[form][0].resetFields();
                    }
                }
            }
            if (endValids.indexOf(false) < 0) {
                this.saveLive();
            }
        },
        resetForm(formName) {
            this.$router.back(-1);
            this.$refs[formName].resetFields();
        },
        // 自定义表单验证
        checkSpace(rule, value, callback) {
            let trim = value.trim();
            if (!trim) {
                callback(new Error("请输入内容"));
            } else {
                callback();
            }
        },
        checkScore(rule, value, callback) {
            if (value == undefined) {
                value = 0;
            }
            if (value < 1 || value > 100) {
                callback(new Error("须是1-100的数字值"));
            } else {
                callback();
            }
        }
    }
};
</script>

